package com.sgb.kjwl.view.ui.activity.enterprise;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;


import com.swgk.core.util.AttachmentStore;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPublishpublicityBinding;
import com.sgb.kjwl.model.entity.NeedDetailsEntity;
import com.sgb.kjwl.model.entity.enterprise.NeedDetailSignUpEntity;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.EditTextUtils;
import com.sgb.kjwl.utils.FileUtils;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.viewmodel.enterprise.PublishPublicityViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import java.io.File;
import java.io.Serializable;

/**
 * 添加公示页面
 */
public class PublishPublicityActivity extends AppActivity {

    private ActivityPublishpublicityBinding mBinding;
    private PublishPublicityViewModel mViewModel;
    private OptionsPickerView optionsPickerView_type;
    // 打开任务管理器
    public static final int REQUESTCODE_OPEN_FILECHOOSER = 102;

    public static void start(Context mContext, NeedDetailSignUpEntity data, NeedDetailsEntity needData) {
        Intent mIntent = new Intent();
        mIntent.setClass(mContext, PublishPublicityActivity.class);
        mIntent.putExtra("data", (Serializable) data);
        mIntent.putExtra("needData", (Serializable) needData);
        mContext.startActivity(mIntent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding.actionBar.setOnBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                com.sgb.kjwl.utils.DialogHelper.showDialog(getActivity(), "温馨提示", "确定要返回吗？", "确定", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                      finish();
                    }
                });
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();

        mViewModel = new ViewModelProvider(this).get(PublishPublicityViewModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_publishpublicity);
        mBinding.setVariable(BR.publishViewmodel, mViewModel);
        mBinding.setLifecycleOwner(this);

        mViewModel.mItemData = (NeedDetailSignUpEntity) getIntent().getSerializableExtra("data");
        mViewModel.needData = (NeedDetailsEntity) getIntent().getSerializableExtra("needData");

        //默认设置是
        mViewModel.choicePublicity.postValue("是");
        initclick();
        setEditextFlag();
        initObsever();
    }


    private void initObsever() {
        mViewModel.ToastShow.observe(this, data -> {
            MToast.showLongToast(this, data);
        });

        mViewModel.showloading.observe(this, type_int -> {
            switch (type_int) {
                case 1:
                    DialogHelper.showProgressDialog(PublishPublicityActivity.this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;

                case 3://结束当前Activit
                    finish();
                    break;
                case 4://提交异常
                    AddNeedQuoteResultActivity.start(this, false, true);
                    finish();
                    break;
            }
        });
    }

    private void initclick() {
        mBinding.linChoicetype.setOnClickListener(this);
        mBinding.tvUploadAnnex.setOnClickListener(this);
    }


    private void setEditextFlag() {
        EditTextUtils.setEditTextFlag(mBinding.tvNote, mBinding.tvTextszie, 300);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_upload_annex:
                Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
                fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
                //设置类型
                fileIntent.setType("application/zip|image/png|application/pdf|application/rar|image/jpeg");
                //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    fileIntent.putExtra(Intent.EXTRA_MIME_TYPES,
                            new String[]{"application/zip", "image/png", "application/pdf", "application/rar", "image/jpeg"});
                }
                startActivityForResult(fileIntent, REQUESTCODE_OPEN_FILECHOOSER);
                break;

            case R.id.lin_choicetype:
                KeyboardUtils.hideSoftInput(PublishPublicityActivity.this);
                if (optionsPickerView_type == null) {
                    mViewModel.initListType();
                    optionsPickerView_type = new OptionsPickerBuilder(PublishPublicityActivity.this, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            mViewModel.choicePublicity.postValue(mViewModel.listType.get(options1).name);
                            mBinding.llGsDay.setVisibility(mViewModel.listType.get(options1).name.equals("是") ? View.VISIBLE : View.GONE);
                        }
                    }).setCancelText("取消").setSubCalSize(15)
                            .setCancelColor(Color.parseColor("#666666"))
                            .setTitleText("")
                            .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                            .setSubmitText("确定")
                            .setSubmitColor(Color.parseColor("#5792FD"))
                            .setTextColorCenter(Color.parseColor("#ff333333"))
                            .setContentTextSize(15)
                            .setLineSpacingMultiplier(2.5f)
                            .setDividerColor(Color.parseColor("#EDEDED"))
                            .setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
                    optionsPickerView_type.setPicker(mViewModel.listType);
                    optionsPickerView_type.setSelectOptions(0);
                }
                optionsPickerView_type.show();
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUESTCODE_OPEN_FILECHOOSER) {//选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                    return;
                }
                handleFileChoose(data);
            }
        }
    }


    private void handleFileChoose(Intent data) {
        Uri uri = data.getData();
//        binding.rlFilename.setVisibility(View.VISIBLE);
        /****
         * //使用第三方应用打开
         */
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            mViewModel.filePath = uri.getPath();
            if (checkFileSize(mViewModel.filePath)) {
                mBinding.tvUploadAnnex.setVisibility(View.GONE);
                mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
                mViewModel.fileName = new File(mViewModel.filePath).getName();
                long fileLength = AttachmentStore.getFileLength(mViewModel.filePath);
                mViewModel.fileSize = UiUtil.bytes2kb(fileLength);
                mViewModel.fileType = FileUtil.getMimeType(new File(mViewModel.filePath));
                mBinding.tvAnnexName.setText(mViewModel.fileName);
                mBinding.tvAnnexSize.setText(mViewModel.fileSize);
                switch (mViewModel.fileType) {
                    case "application/zip":
                    case "application/rar":
                        Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                        break;
                    case "image/png":
                    case "image/jpeg":
                        Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/pdf":
                        Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                        break;
                }
                mViewModel.uploadSingleImage(this, new File(mViewModel.filePath), 1, true);
            }
            LogUtil.d("TAG", "handleFileChoose uri.getScheme():" + mViewModel.filePath);
            return;
        }
        /***
         * //4.4以后
         */
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            mViewModel.filePath = FileUtils.getPath(this, uri);
        } else {//4.4以下下系统调用方法
            mViewModel.filePath = FileUtils.getRealPathFromURI(uri, this);
        }
        if (checkFileSize(mViewModel.filePath)) {
            mBinding.tvUploadAnnex.setVisibility(View.GONE);
            mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
            mViewModel.fileName = new File(mViewModel.filePath).getName();
            long fileLength = AttachmentStore.getFileLength(mViewModel.filePath);
            mViewModel.fileSize = UiUtil.bytes2kb(fileLength);
            mViewModel.fileType = FileUtil.getMimeType(new File(mViewModel.filePath));
            mBinding.tvAnnexName.setText(mViewModel.fileName);
            mBinding.tvAnnexSize.setText(mViewModel.fileSize);
            switch (mViewModel.fileType) {
                case "application/zip":
                case "application/rar":
                    Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                    break;
                case "image/png":
                case "image/jpeg":
                    Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                    break;
                case "application/pdf":
                    Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                    break;
            }
            mViewModel.uploadSingleImage(this, new File(mViewModel.filePath), 1, true);
        }
        LogUtil.d("TAG", "handleFileChoose filePath:" + mViewModel.filePath);
    }


    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private boolean checkFileSize(String filePath) {
        float sizeCount = 0f;
        long fileLength = AttachmentStore.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > 20) {
                    MToast.showToast(this, "请上传20MB内的文件！");
                    return false;
                }
            }
        }
        return true;
    }

}
